package edu.ynu.se.xiecheng.achitectureclass.project.service;

import edu.ynu.se.xiecheng.achitectureclass.project.dao.CameraTokenDAO;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class CameraTokenService {

    @Autowired
    private CameraTokenDAO cameraTokenDAO;

    @Autowired
    private RestTemplate restTemplate;

    // 获取萤石云 token 的 URL
    private static final String CAMERA_TOKEN_URL = "http://42.193.14.241:7000/ysapi/subAccount/getToken";

    // 萤石云子账户 ID
    private static final String ACCOUNT_ID = "1ca7f0ab24ba41b291346347ec30140e";

    /**
     * 获取或刷新摄像头的访问 token
     *
     * @return 有效的 token
     */
    public String getOrRefreshCameraToken() {
        Optional<Token> optionalToken = cameraTokenDAO.findByTypeAndIsDeleted("camera", 0);
        if (optionalToken.isPresent()) {
            Token token = optionalToken.get();
            // 假设 token 没有过期时间字段，直接返回
            return token.getToken();
        }

        // 如果 token 不存在或已过期，则重新获取 token
        return refreshCameraToken();
    }

    /**
     * 刷新并保存摄像头的 token
     *
     * @return 保存的 Token 实体
     */
    public Token refreshAndSaveCameraToken() {
        // 调用萤石云接口获取 token
        String newTokenValue = refreshCameraToken();

        // 保存 token 到数据库
        Token token = new Token();
        token.setToken(newTokenValue);
        token.setType("camera"); // 标记为摄像头的 token
        token.setIsDeleted(0); // 标记为未删除
        return cameraTokenDAO.save(token);
    }

    /**
     * 刷新摄像头的访问 token
     *
     * @return 新的 token
     */
    private String refreshCameraToken() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("accountId", ACCOUNT_ID);

        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

        ResponseEntity<Map> response = restTemplate.postForEntity(CAMERA_TOKEN_URL, requestEntity, Map.class);

        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            Map<String, Object> data = (Map<String, Object>) response.getBody().get("data");
            return (String) data.get("accessToken");
        }

        throw new RuntimeException("Failed to refresh camera token: " + response.getStatusCode());
    }
}